package com.company.beauty.area.util;

import com.company.beauty.area.support.AreaTree;
import com.company.nuwa.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * <p>区域工具类</p >
 *
 * @author youyoukele
 * @version 1.0
 * @date 2024/4/25 15:35
 */
@Slf4j
public class AreaUtil {

    private static AreaTree AREA_TREE = null;

    private static final String AREA_DATA;

    static {
        try {
            log.info("init area ...");
            // 使用类加载器加载资源文件
            InputStream inputStream = AreaUtil.class.getClassLoader().getResourceAsStream("area.json");
            // 读取资源文件内容为字符串
            AREA_DATA = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
            // 关闭输入流
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
            log.info("area data json:{}", AREA_DATA);
        } catch (IOException e) {
            log.error("Failed to load area.json file", e);
            throw new RuntimeException("Failed to load area.json file", e);
        }
    }

    /**
     * 获取完整区域数据，以树形结构返回
     *
     * @return
     */
    public static synchronized AreaTree getTree() {
        if (AREA_TREE == null) {
            AREA_TREE = JsonUtils.jsonToObject(AREA_DATA, AreaTree.class);
        }
        return AREA_TREE;
    }

    public static void main(String[] args) {
        System.out.println(JsonUtils.objectToJson(getTree()));
    }
}
